#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 运行：./tcpserver server-ip server-port

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " local-ip, server-port" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr<<"socket error!"<<std::endl;
        exit(1);
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server_addr.sin_addr);

    int n = ::connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
    if(n < 0)
    {
        std::cerr<<"connect error!"<<std::endl;
        exit(2);
    }

    while(true)
    {
        std::string message;
        std::cout<<"Enter # ";
        std::getline(std::cin, message);

        write(sockfd, message.c_str(), message.size());

        char echo_buffer[1024];
        int n = read(sockfd, echo_buffer, sizeof(echo_buffer) -1);
        if(n > 0)
        {
            echo_buffer[n] = 0;
            std::cout<<echo_buffer<<std::endl;
        }
        else
        {
            break;
        }
    }

    ::close(sockfd);
    return 0;
}